package util

import (
	"fmt"
	"log"

	"github.com/xuri/excelize/v2"
)

func Read(filename string, sheetName string) ([]map[string]string, error) {
	// 打开 Excel 文件
	f, err := excelize.OpenFile(filename)
	if err != nil {
		log.Fatal("Failed to open file:", err)
		return nil, err
	}
	defer f.Close()

	// 获取所有行
	records, err := f.GetRows(sheetName)
	if err != nil {
		log.Printf("Failed to get rows from sheet %s: %v", sheetName, err)
		return nil, err
	}
	if len(records) == 0 {
		log.Fatal("工作表为空")
		return nil, fmt.Errorf("工作表数据行为：%d", 0)
	}

	// 打印表头
	header := make([]string, len(records)-1)
	result := make([]map[string]string, len(records)-1)
	//循环读取records即可，records是二维切片
	for i, record := range records {
		if i == 0 {
			for _, field := range record {
				header = append(header, field)
			}
			continue
		}
		item := make(map[string]string, len(record))
		for i, field := range record {
			item[header[i]] = field
		}
		result = append(result, item)
	}
	log.Fatal("读取文件成功")
	return result, nil
}

func Write(data []map[string]string, sheetName string, filename string) error {
	if len(data) == 0 {
		return nil
	}

	f := excelize.NewFile()
	defer f.Close()

	// 创建工作表
	index, err := f.NewSheet(sheetName)
	if err != nil {
		return err
	}

	//获取头顺序
	header := make([]string, len(data[0]))
	for key, _ := range data[0] {
		header = append(header, key)
	}
	//组装数据，包括头
	datas := make([][]string, len(data))
	datas = append(datas, header)
	for _, item := range data {
		data := make([]string, len(header))
		for _, key := range header {
			data = append(data, item[key])
		}
		datas = append(datas, data)
	}

	// 设置表头样式
	headerStyle, err := f.NewStyle(&excelize.Style{
		Font:      &excelize.Font{Bold: true, Color: "FFFFFF"},
		Fill:      excelize.Fill{Type: "pattern", Color: []string{"4F81BD"}, Pattern: 1},
		Alignment: &excelize.Alignment{Horizontal: "center"},
	})
	if err != nil {
		return err
	}
	//写数据到文件
	for rowIndex, rowData := range datas {
		for colIndex, cellData := range rowData {
			cell, _ := excelize.CoordinatesToCellName(colIndex+1, rowIndex+1)
			err := f.SetCellValue(sheetName, cell, cellData)
			if err != nil {
				return err
			}
			if rowIndex == 0 {
				err := f.SetCellStyle(sheetName, cell, cell, headerStyle)
				if err != nil {
					return err
				}
			}
		}
	}
	f.SetActiveSheet(index)

	if err := f.SaveAs(filename); err != nil {
		println(err.Error())
	}
	return nil
}
